package com.example.springboot;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.concurrent.atomic.AtomicInteger;

@RestController
@Slf4j
public class HelloController {

	private Integer intMember = 0;
	private static Integer intStatic = 0;
	private AtomicInteger autoMember = new AtomicInteger(0);
	static private AtomicInteger autoStatic = new AtomicInteger(0);
	private ThreadLocal<Integer> localMember = new ThreadLocal<>();
	private static ThreadLocal<Integer> localStatic = new ThreadLocal<>();

	@RequestMapping("/")
	public String index() {
		return "hello world";
	}

	@RequestMapping("/all")
	public String all() {
		intMember ++;
		intStatic++;
		String re = intMember + " " + intStatic + " " + autoMember.incrementAndGet() + " " + autoStatic.incrementAndGet();
		log.info(re);
		return re;
	}
	/**
	 * 高并发计数 1000 少 52
	 * @return
	 */
	@RequestMapping("/intMember")
	public String intMember() {
		intMember ++;
		String re = intMember+"";
		log.info(re);
		return re;
	}
	/**
	 * 高并发计数 1000 少 50
	 * @return
	 */
	@RequestMapping("/intStatic")
	public String intStatic() {
		intStatic++;
		String re = intStatic+"";
		log.info(re);
		return re;
	}
	/**
	 * 高并发能正常计数
	 * @return
	 */
	@RequestMapping("/autoMember")
	public String autoMember() {
		String re = autoMember.incrementAndGet()+"";
		log.info(re);
		return re;
	}
	/**
	 * 高并发能正常计数
	 * @return
	 */
	@RequestMapping("/autoStatic")
	public String autoStatic() {
		String re = autoStatic.incrementAndGet()+"";
		log.info(re);
		return re;
	}

	/**
	 * 高并发无日志输出
	 * @return
	 */
	@RequestMapping("/localMember")
	public String localMember() {
		Integer integer = localMember.get();
		if (null == integer) {
			integer = new Integer(0);
			localMember.set(integer);
		}
		integer++;
		String re = integer+"";
		if (integer > 1) {
			log.info(re);
		}
		return re;
	}

	/**
	 * 高并发无日志输出
	 * @return
	 */
	@RequestMapping("/localStatic")
	public String localStatic() {
		Integer integer = localStatic.get();
		if (null == integer) {
			integer = new Integer(0);
			localStatic.set(integer);
		}
		integer++;
		String re = integer+"";
		if (integer > 1) {
			log.info(re);
		}
		return re;
	}
}
